/**
 * Created by LeungZ on 2016/8/10.
 */
import tmp from '../form/pause.html'
import ctrl from '../form/pause.ctrl.js'

class Detail {
    constructor(detail, $uiModal, resource, $filter, $timeout, nodeSrv, ctgNotification, $scope, $stateParams, $window) {
        "ngInject";
        this._uiModal = $uiModal;
        this._dateFormat = $filter("date");
        this._nodeSrv = nodeSrv;
        this._notification = ctgNotification;
        this._timeout = $timeout;
        this.timer = '';
        this.dbCode = $stateParams.kDbCode;
        this.addr = $stateParams.ip;
        var winTimer = '';

        if (detail) {
            this.nodeStatus = _.findWhere(detail.status.conditions, {type: 'Ready'}).status == 'True';
            this.labels = this.labelToArray(detail.metadata.labels);
            this.createTime = detail.metadata.creationTimestamp;
            this.capacity = detail.status.capacity;
            this.nodeInfo = this.infoToArray(detail.status.nodeInfo);
            this.externalID = detail.spec.externalID;
        }

        if (resource) {
            this.memData = [{
                name: '占用内存',
                datapoints: []
            }, {
                name: '总内存',
                datapoints: []
            }];
            this.memConf = {
                type: 'area',
                color: ['#5093e1', '#CCC'],
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> <i style="color:#5093e1" class="fa fa-circle"></i> {a0} {c0} MB' +
                    ' <br/> <i style="color:#CCC" class="fa fa-circle"></i> {a1} {c1} MB'
                },
                notMerge: true
            };

            this.cpuData = [{
                name: 'CPU使用率',
                datapoints: []
            }];
            this.cpuConf = {
                type: 'line',
                color: ['#50c14e'],
                yAxis: {
                    max: 100
                },
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> <i style="color:#50c14e" class="fa fa-circle"></i> CPU已使用 {c}%'
                },
                notMerge: true,
                series: [{
                    smooth: true
                }]
            };

            this.netTypes = [{name: "收发流量", type: 'bytes'}, {name: "收发丢包数", type: 'dropped'}, {
                name: "收发错误数",
                type: 'errors'
            }, {name: "收发包数", type: 'packets'}];
            this.networkData = {};
            angular.forEach(resource[0].network, _network => {
                this.networkData[_network.name] = {};
                angular.forEach(this.netTypes, _type=> {
                    this.networkData[_network.name][_type.type] = [{
                        name: '接收',
                        datapoints: []
                    }, {
                        name: '发送',
                        datapoints: []
                    }];
                });
            });


            this.networkConf = {
                type: 'line',
                color: ['#2ec7c9', '#b6a2de'],
                grid: {
                    bottom: "30"
                },
                tooltip: {
                    formatter: '{b} <br/> <i style="color:#2ec7c9" class="fa fa-circle"></i> {a0} {c0} 字节' +
                    ' <br/> <i style="color:#b6a2de" class="fa fa-circle"></i> {a1} {c1} 字节'
                },
                notMerge: true,
                series: [{
                    smooth: true
                }]
            };

            this.fileData = [];
            this.fileConf = {
                type: 'pie',
                legend: {
                    orient: 'horizontal',
                    y: 'bottom',
                    x: 'center'
                },
                notMerge: true,
                tooltip: {
                    formatter: '{a}<br/> <i style="color:#2ec7c9" class="fa fa-circle"></i> {b} {c0} MB,占比{d}%'
                }
            };

            this.unschedulable = resource.unschedulable;
            this.formatCpuData(resource[0]);
            this.formatMemData(resource[0]);
            this.formatNetworkData(resource[0].network);
            this.formatFileData(resource[0].FileSystem);
            this.renderChart('cpu');
            this.resDataRefresh();
        }

        $window.onresize = () => {
            $timeout.cancel(winTimer);
            winTimer = $timeout(() => {
                this.chartModel().resize();
            }, 50, false);
        };

        $scope.$on('$destroy', () => {
            this._timeout.cancel(this.timer);
            $window.onresize = null;
        });
    }

    infoToArray(map) {
        let array = [];
        angular.forEach(Object.keys(map), function (ele) {
            array.push({
                key: ele,
                val: map[ele]
            })
        });
        return array;
    }

    labelToArray(map) {
        let array = [];
        angular.forEach(Object.keys(map), function (ele) {
            array.push(ele + '=' + map[ele]);
        });
        return array;
    }

    stopNode() {
        this._uiModal.open({
            templateUrl: tmp,
            controller: ctrl,
            controllerAs: 'vm',
            windowClass: 'alert-dialog alert-dialog-ctg',
            resolve: {
                nodeIp: () => {
                    return this.addr;
                }
            }
        }).result.then(() => {
                this.unschedulable = 'loading';
                this._nodeSrv.stopNode({
                    ip: this.addr,
                    code: this.dbCode
                }).then(data => {
                    this.unschedulable = data.unschedulable;
                    this._notification.success('停用宿主机 ' + this.addr + ' 成功.');
                }).catch(data => {
                    this.unschedulable = false;
                    this._notification.error('停用宿主机 ' + this.addr + ' 失败.');
                })
            })
    }

    startNode() {
        this.unschedulable = 'loading';
        this._nodeSrv.startNode({
            ip: this.addr,
            code: this.dbCode
        }).then(data => {
            this.unschedulable = data.unschedulable;
            this._notification.success('启用宿主机 ' + this.addr + ' 成功.');
        }).catch(data => {
            this.unschedulable = true;
            this._notification.error('启用宿主机 ' + this.addr + ' 失败.');
        })
    }

    formatNetworkData(network) {
        let transimit = {};
        let receive = {};

        angular.forEach(network, _network => {
            angular.forEach(this.netTypes, ele=> {
                transimit[ele.type] = [];
                receive[ele.type] = [];

                angular.forEach(_network.nodeNetworkStamp, netPoint => {
                    transimit[ele.type].push({
                        x: this._dateFormat(netPoint.timestamp, 'HH:mm:ss'),
                        y: netPoint['tx' + ele.type.replace(ele.type[0], ele.type[0].toUpperCase())]
                    });
                    receive[ele.type].push({
                        x: this._dateFormat(netPoint.timestamp, 'HH:mm:ss'),
                        y: netPoint['rx' + ele.type.replace(ele.type[0], ele.type[0].toUpperCase())]
                    })
                });
                this.networkData[_network.name][ele.type][0].datapoints = receive[ele.type];
                this.networkData[_network.name][ele.type][1].datapoints = transimit[ele.type];
            });
        });

        this.netAdapts = Object.keys(this.networkData);
        if (!this.netAdapt) this.netAdapt = this.netAdapts[0];
    }

    formatCpuData(cpu) {
        let usedCpu = [];
        angular.forEach(cpu.cpuPerTimes, _cpu => {
            usedCpu.push({
                x: this._dateFormat(_cpu.timestamp, 'HH:mm:ss'),
                y: _cpu.usage
            });
        });
        this.cpuData[0].datapoints = usedCpu;
        this.cpuUsage = cpu.totalCpuUsage;
    }

    formatMemData(memory) {
        let usedMem = [];
        let totalMem = [];
        angular.forEach(memory.memoryPerTimes, mem => {
            usedMem.push({
                x: this._dateFormat(mem.timestamp, 'HH:mm:ss'),
                y: mem.usage
            });
            totalMem.push({
                x: this._dateFormat(mem.timestamp, 'HH:mm:ss'),
                y: memory.totalMemory
            })
        });
        this.memData[0].datapoints = usedMem;
        this.memData[1].datapoints = totalMem;
        this.memUsage = ((memory.memoryUsage / memory.totalMemory) * 100).toFixed(0);
    }

    formatFileData(files) {
        angular.forEach(files, _file => {
            this.fileData[_file.device] = [{
                name: _file.device,
                datapoints: [{
                    x: 'usage',
                    y: _file.capacity - _file.available
                }, {
                    x: 'availability',
                    y: _file.available
                }]
            }];
        });
        this.fileAdapts = Object.keys(this.fileData);
        if (!this.fileAdapt) this.fileAdapt = this.fileAdapts[0];
    }

    resDataRefresh() {
        this.timer = this._timeout(this.getResData.bind(this), 10000);
    }

    getResData() {
        this._nodeSrv.queryNodeResource({
            nodeips: [this.addr],
            clusterCode: this.dbCode
        }).then(data => {
            this.nodeStatus = data[0].ready;
            this.formatCpuData(data[0]);
            this.formatMemData(data[0]);
            this.formatNetworkData(data[0].network);
            this.formatFileData(data[0].FileSystem);
            this.resDataRefresh();
        }).catch(data => {
            this._notification.error('获取宿主机资源数据有误.');
        });
    }

    renderChart(type, pass) {
        if (this[type + 'Data'] && this[type + 'Conf'] && (type != this.chartType || pass)) {
            this.chartType = type;
            if (type == 'network') {
                this.netType = this.netTypes[0].type;
                this.chartData = this[type + 'Data'][this.netAdapt][this.netType] || [{
                        name: '接收',
                        datapoints: []
                    }, {
                        name: '发送',
                        datapoints: []
                    }];
            } else if (type == 'file') {
                this.chartData = this[type + 'Data'][this.fileAdapt];
            } else {
                this.chartData = this[type + 'Data'];
            }
            this.chartConf = this[type + 'Conf'];
            this.chartConf.tooltip.show = !!this.chartData[0].datapoints.length;
        }
    }

    changeType(type) {
        this.netType = type;
        this.chartData = this['networkData'][this.netAdapt][this.netType];
    }
}
export default Detail